<template>
  <div class="add-wrapper">
    <el-page-header
      @back="goBack"
      :content="isAdd ? '创建供应商' : '编辑供应商'"
    >
    </el-page-header>
    <div class="form-wrapper">
      <div class="top-form">
        <div class="descLabel">基本信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item v-if="!isAdd" prop="supplier_serial" label="供应商编号">
            <el-input v-model="dataForm.supplier_serial" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="供应商名称">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="legal_person" label="法人代表">
            <el-input v-model="dataForm.legal_person"></el-input>
          </el-form-item>
          <el-form-item prop="username" label="联系人">
            <el-input v-model="dataForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="联系电话">
            <el-input v-model="dataForm.phone"></el-input>
          </el-form-item>

          <div class="descLabel">财务信息</div>
          <el-form-item prop="bank_deposit" label="开户银行">
            <el-input v-model="dataForm.bank_deposit"></el-input>
          </el-form-item>
          <el-form-item prop="bank_account" label="银行账号">
            <el-input v-model="dataForm.bank_account"></el-input>
          </el-form-item>
          <el-form-item prop="duty_paragraph" label="纳税人识别号">
            <el-input v-model="dataForm.duty_paragraph"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="size-form padTop20">
        <el-form @submit.native.prevent label-width="120px">
          <div class="descLabel">供应商物料</div>
          <el-form-item label="">
            <el-button type="primary" @click="handleAdd">添加</el-button>
          </el-form-item>
          <el-form-item label="">
            <el-table :data="generateList" border style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                header-align="center"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column
                prop="material_serial"
                label="物料编码"
                header-align="center"
                align="center"
                width="240"
              ></el-table-column>
              <el-table-column
                prop="name"
                label="物料"
                header-align="center"
                align="center"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="specifications_model"
                label="规格型号"
                header-align="center"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="material_type_str"
                label="物料类别"
                header-align="center"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="material_attr_str"
                label="物料属性"
                header-align="center"
                align="center"
              ></el-table-column>
              <el-table-column
                :label="$t('handle')"
                fixed="right"
                header-align="center"
                align="center"
                width="150"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-bottom: 36px">
        <el-button @click="goBack" style="margin-left: 45%; margin-top: 36px"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="dataFormSubmitHandle()"
          style="margin-left: 21px"
          >确定</el-button
        >
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="查看">
      <img width="100%" :src="dialogImageUrl" class="avatar" />
    </el-dialog>
    <MaterialChoose
      v-if="addOrUpdateVisible"
      ref="bomFit"
      @handleClose="handleClose"
      @handleConfirm="fitConfirm"
    ></MaterialChoose>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { isMobile } from '@/utils/validate'
import MaterialChoose from '@/components/material-choose'
import { getSupplierBomDetail, addSupplier, deleteBomFit } from '@/api'
export default {
  components: {
    MaterialChoose,
  },
  data() {
    return {
      dataForm: {
        id: '',
        name: '',
        legal_person: '',
        username: '',
        phone: '',
        bank_deposit: '',
        bank_account: '',
        duty_paragraph: '',
      },
      dialogImageUrl: '',
      dialogVisible: false,
      addOrUpdateVisible: false,
      generateList: [],
      isAdd: true,
    }
  },
  computed: {
    dataRule() {
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(
            new Error(
              this.$t('validate.format', { attr: this.$t('user.mobile') })
            )
          )
        }
        callback()
      }
      return {
        name: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        legal_person: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        username: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        phone: [{ required: true, validator: validateMobile, trigger: 'blur' }],
      }
    },
  },
  activated() {
    this.$refs['dataForm'].resetFields()
    this.generateList = []
    const id = this.$route.params.id
    this.dataForm.id = id
    if (id) {
      this.fetchDetail(id)
      this.isAdd = false
    }
  },
  methods: {
    handleDelete(row) {
      const { id } = row
      let arr = []
      arr = this.generateList.filter((item) => item.id !== id)
      this.generateList = arr
    },
    fitConfirm(row) {
      const arr = []
      row.forEach((item) => {
        const {
          id,
          material_serial,
          name,
          specifications_model,
          material_type_str,
          material_attr_str,
        } = item
        const temp = {
          id,
          //   id: 0,
          material_serial,
          name,
          specifications_model,
          material_type_str,
          material_attr_str,
        }
        arr.push(temp)
      })
      console.log(this.generateList)
      console.log(arr)
      this.generateList = [...this.generateList, ...arr]
    },
    handleClose() {
      this.addOrUpdateVisible = false
    },
    handleClose() {
      this.addOrUpdateVisible = false
    },
    handleAdd() {
      this.addOrUpdateVisible = true
    },
    async fetchDetail(id) {
      const params = {
        id,
      }
      const res = await getSupplierBomDetail(params)
      if (res?.status === 1) {
        const data = res?.data || {}
        const { material_list, ...info } = data
        this.dataForm = info
        this.generateList = material_list
      }
    },
    goBack() {
      this.$router.go(-1)
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (!valid) {
            return false
          }
          const params = {}
          const {
            name,
            username,
            legal_person,
            phone,
            bank_deposit,
            bank_account,
            duty_paragraph,
          } = this.dataForm
          params.name = name
          params.username = username
          params.legal_person = legal_person
          params.phone = phone
          if (bank_deposit) params.bank_deposit = bank_deposit
          if (bank_account) params.bank_account = bank_account
          if (duty_paragraph) params.duty_paragraph = duty_paragraph
          params.id = this.dataForm.id ? this.dataForm.id : 0
          const arr = []
          this.generateList.forEach((item) => arr.push(item.id))
          params.material_ids = arr
          console.log(params)
          const res = await addSupplier(params)
          if (res?.status === 1) {
            this.$message.success(res?.msg || '操作成功')
            this.$refs['dataForm'].resetFields()
            this.$router.go(-1)
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
  // watch: {
  //   'dataForm.type' (val) {
  //     this.$refs['dataForm'].clearValidate()
  //   }
  // },
}
</script>

<style lang="scss" scoped>
.add-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  .form-wrapper {
    ::v-deep .el-select {
      width: 100%;
    }

    .top-form {
      width: 50%;
      margin-top: 36px;

      .picDes {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
        line-height: 18px;
      }
    }
  }
}
</style>
